/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import Model.DPICard;
import Model.DPIinfo;
import Controller.Reader.ReaderListener;
import Controller.StaxWriter;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.smartcardio.CardException;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


    /**
 *
 * @author giovannirojas
 */
public class DPIViewer extends javax.swing.JFrame implements ReaderListener {

    DPICard card = null;
    DPIinfo info = null;
    Image image = null;
    
    /**
     * Creates new form DPIViewer
     */
    public DPIViewer() {
        initComponents();
        
        // Cuando inicio solo mostrare el panel que dice que ingrese el DPI 
        tabPanels.removeAll();
        tabPanels.add(panelStart);
        
        putImage(true); // Coloco la imagen de loading. 
        blankField();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tabPanels = new javax.swing.JTabbedPane();
        panelStart = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        infoPanel = new javax.swing.JPanel();
        photoPanel = new JPanel(){

            public void paintComponent(Graphics gio)
            {
                super.paintComponent(gio);
                if(image != null) {
                    gio.drawImage(image, (this.getWidth()-image.getWidth(null))/2, (this.getHeight()-image.getHeight(null))/2, this);
                }
            };

        }
        ;
        jLayeredPane1 = new javax.swing.JLayeredPane();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        sexoField = new javax.swing.JTextField();
        nacimientoField = new javax.swing.JTextField();
        nameField = new javax.swing.JTextField();
        apellidoField = new javax.swing.JTextField();
        dpiField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("¿Are you?      Zero Invention");

        tabPanels.setTabPlacement(javax.swing.JTabbedPane.BOTTOM);

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/insertDpi.png"))); // NOI18N

        jLabel7.setFont(new java.awt.Font("Kannada MN", 1, 48)); // NOI18N
        jLabel7.setText("Ingrese el DPI en el lector.");

        org.jdesktop.layout.GroupLayout panelStartLayout = new org.jdesktop.layout.GroupLayout(panelStart);
        panelStart.setLayout(panelStartLayout);
        panelStartLayout.setHorizontalGroup(
            panelStartLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelStartLayout.createSequentialGroup()
                .addContainerGap(188, Short.MAX_VALUE)
                .add(panelStartLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, panelStartLayout.createSequentialGroup()
                        .add(jLabel6)
                        .add(306, 306, 306))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, panelStartLayout.createSequentialGroup()
                        .add(jLabel7)
                        .add(121, 121, 121))))
        );
        panelStartLayout.setVerticalGroup(
            panelStartLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelStartLayout.createSequentialGroup()
                .add(76, 76, 76)
                .add(jLabel6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 203, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(jLabel7, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(27, Short.MAX_VALUE))
        );

        tabPanels.addTab("Ask DPI", panelStart);

        photoPanel.setBackground(new java.awt.Color(128, 128, 128));
        photoPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        org.jdesktop.layout.GroupLayout photoPanelLayout = new org.jdesktop.layout.GroupLayout(photoPanel);
        photoPanel.setLayout(photoPanelLayout);
        photoPanelLayout.setHorizontalGroup(
            photoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 250, Short.MAX_VALUE)
        );
        photoPanelLayout.setVerticalGroup(
            photoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 339, Short.MAX_VALUE)
        );

        jLayeredPane1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel1.setText("<html>Fecha de <br>Nacimiento");
        jLabel1.setBounds(20, 230, 100, 30);
        jLayeredPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel2.setText("Nombre :");
        jLabel2.setBounds(20, 20, 110, 30);
        jLayeredPane1.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel3.setText("Apellido :");
        jLabel3.setBounds(20, 70, 110, 30);
        jLayeredPane1.add(jLabel3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel4.setText("DPI :");
        jLabel4.setBounds(20, 120, 110, 30);
        jLayeredPane1.add(jLabel4, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel5.setText("Sexo:");
        jLabel5.setBounds(20, 170, 110, 30);
        jLayeredPane1.add(jLabel5, javax.swing.JLayeredPane.DEFAULT_LAYER);

        sexoField.setText("MASCULINO");
        sexoField.setEnabled(false);
        sexoField.setBounds(140, 170, 360, 40);
        jLayeredPane1.add(sexoField, javax.swing.JLayeredPane.DEFAULT_LAYER);

        nacimientoField.setText("11ABR1994");
        nacimientoField.setEnabled(false);
        nacimientoField.setBounds(140, 220, 360, 40);
        jLayeredPane1.add(nacimientoField, javax.swing.JLayeredPane.DEFAULT_LAYER);

        nameField.setText("Geovanni Gerardo Rodolfo Eduardo");
        nameField.setEnabled(false);
        nameField.setBounds(140, 20, 360, 40);
        jLayeredPane1.add(nameField, javax.swing.JLayeredPane.DEFAULT_LAYER);

        apellidoField.setText("Rojas Mazariegos");
        apellidoField.setEnabled(false);
        apellidoField.setBounds(140, 70, 360, 40);
        jLayeredPane1.add(apellidoField, javax.swing.JLayeredPane.DEFAULT_LAYER);

        dpiField.setText("2340667410101");
        dpiField.setEnabled(false);
        dpiField.setBounds(140, 120, 360, 40);
        jLayeredPane1.add(dpiField, javax.swing.JLayeredPane.DEFAULT_LAYER);

        org.jdesktop.layout.GroupLayout infoPanelLayout = new org.jdesktop.layout.GroupLayout(infoPanel);
        infoPanel.setLayout(infoPanelLayout);
        infoPanelLayout.setHorizontalGroup(
            infoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(infoPanelLayout.createSequentialGroup()
                .add(15, 15, 15)
                .add(photoPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(28, 28, 28)
                .add(jLayeredPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 583, Short.MAX_VALUE)
                .addContainerGap())
        );
        infoPanelLayout.setVerticalGroup(
            infoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, infoPanelLayout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(infoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(photoPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jLayeredPane1))
                .add(19, 19, 19))
        );

        tabPanels.addTab("Information", infoPanel);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(tabPanels, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 909, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(tabPanels))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DPIViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DPIViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DPIViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DPIViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DPIViewer().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField apellidoField;
    private javax.swing.JTextField dpiField;
    private javax.swing.JPanel infoPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JTextField nacimientoField;
    private javax.swing.JTextField nameField;
    private javax.swing.JPanel panelStart;
    private javax.swing.JPanel photoPanel;
    private javax.swing.JTextField sexoField;
    private javax.swing.JTabbedPane tabPanels;
    // End of variables declaration//GEN-END:variables

    @Override
    public void inserted(DPICard card) {
        
        System.out.println("Card Inserted");
           
        
        try {
            // Verifico que sea un dpi official, o bien un dpi, sino no la leo. 
            if (card.isOficialDPI()){
                
                // Oculto el start y muestro la informacion
                tabPanels.removeAll();
                tabPanels.add(infoPanel);  
                
                // Pongo el loading 
                putImage(true);
                
                
                this.card = card;
                info = card.readDPIinfo();
                
                
                // put the data 
                putData(info);
                putImage(false);
                
                
                while (card.isCardIn() ) {
                
                    // mientras este una tarjeta dentro. 
                    
                }
            }
            
  
        } catch (CardException e) {
            
            JOptionPane.showMessageDialog(null, "<html><body><pre><p style='width: 600px;'> Error al leer DPI  <br/>"+e+"</p></pre></body></html>","Error en lectura DPI", 0);
        
        }
    }

    @Override
    public void removed() {
        
        System.out.println("Card removed");
        /* Mando a ejecutar el codigo para crear el XML */
        if (info!= null) {
            StaxWriter configFile = new StaxWriter(info);

            try {
              configFile.saveConfig();
            } catch (Exception e) {
              e.printStackTrace();
            }
        }
        // Coloco la informacion en null. 
        card = null;
        info = null;
        // Coloco de nuevo el panel inicial 
        tabPanels.removeAll();
        tabPanels.add(panelStart);
        // set the loading image. 
        putImage(true);
        blankField();
        
        
        
    }
/*
 * Lo que hace esto es poner los datos en blanco. 
 */  
private void blankField(){
    nameField.setText("");
    apellidoField.setText("");
    dpiField.setText("");
    sexoField.setText("");
    nacimientoField.setText("");
    
}    
/*
 * Lo que  hace este metodo es colocar toda la informacion de 
 * la persona en los campos segun sea el caso. 
 */    
private void putData(DPIinfo info){
        nameField.setText(info.getPrimerNombre().replace("  ", "")+" "+info.getSegundoNombre().replace("  ", "")+" "+info.getTercerNombre().replace("  ", ""));
        apellidoField.setText(info.getPrimerApellido().replace("  ", "")+" "+info.getSegundoApellido().replace("  ", ""));
        dpiField.setText(info.getDpi());
        sexoField.setText(info.getSexo());
        nacimientoField.setText(info.getNacimiento());

}
/*
 * Lo que hace esto es colocar cuando necesite el loading 
 * si la imagen ya cargo entonces colocare la imagen del sujeto 
 * sino pues mando verdadero y coloco el loading. 
 */
private void putImage(boolean loading){
    
    {
        if (loading)
            this.image = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/Imagenes/loading.gif"));
        else 
            this.image = info.getPhoto(); // have to work on it 
        repaint();
    }
    
}


}
